<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="单位名称" prop="unitName">
        <el-input v-model="queryParams.unitName" placeholder="请输入单位名称" clearable size="small"
          @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item label="单位类型" prop="unitType">
        <el-select v-model="queryParams.unitType" placeholder="请选择单位类型" clearable size="small" @change="handleQuery">
          <el-option v-for="type in unitTypeOptions" :key="type.unittypeId" :label="type.unittypeName"
            :value="type.unittypeId"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="查询状态" prop="searchDoingStatus">
        <el-select v-model="queryParams.searchDoingStatus" placeholder="请选择状态" clearable size="small"
          @change="handleStatus">
          <el-option v-for="item in searchDoingStatus" :key="item.value" :label="item.label"
            :value="item.value"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" plain icon="el-icon-check" size="mini" @click="handleSend"
          v-hasPermi="['system:unit:add']">发送短信</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>
    <el-row v-if="valueID!='15'">
      <el-table v-loading="loading" :data="unitList" @selection-change="handleSelectionChange">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="序号" align="left" prop="unitSort" width="100" />
        <el-table-column label="单位名称" align="left" prop="unitName" width="320" />
        <!-- <el-table-column label="中签次数" align="center" prop="unitNum" /> -->
        <el-table-column label="法定代表人" align="left" prop="unitRepresentative" />
        <el-table-column
          label="法定代表人联系电话"
          align="left"
          prop="unitRepresentativePhone"
        />
        <!-- <el-table-column label="中签倍率" align="center" prop="multipleNum" /> -->
        <el-table-column label="联系人" align="left" prop="unitLinkman" />
        <el-table-column label="联系电话" align="left" prop="unitPhone" />
        <el-table-column label="单位类型" align="left" prop="unitBank" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="scope">
            <el-button size="mini" type="text" icon="el-icon-circle-plus-outline"
              @click="handleDetail(scope.row)">单位详情</el-button>
            <!-- <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
              v-hasPermi="['system:unit:edit']">修改</el-button>
            <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
              v-hasPermi="['system:unit:remove']">删除</el-button> -->
          </template>
        </el-table-column>
      </el-table>
    </el-row>
    <el-row v-else>
        <el-table v-loading="loading" :data="agentList" @selection-change="handleSelectionChange">
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="招标人代表名称" align="left" prop="name" />
            <el-table-column label="公司名称" align="left" prop="company" />
            <el-table-column label="专业类别" align="left" prop="professionType" />
            <el-table-column label="职称专业" align="left" prop="profession" />
            <el-table-column label="电话" align="center" prop="telphone" />
            <el-table-column label="身份证号" align="left" width="200" prop="idcard" />
        </el-table>
    </el-row>
    <pagination v-show="total > 0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize"
      @pagination="getList" />
    <!-- 添加或修改单位信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="600px" append-to-body :close-on-click-modal="false">
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="短信类型" prop="messageType">
              <el-select v-model="form.messageType" placeholder="请选择短信类型" clearable size="small" style="width: 100%;">
                <el-option value="SMS_460930557" label="工作通知">工作通知</el-option>
                <el-option value="SMS_460670386" label="会议通知">会议通知</el-option>
              </el-select>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="名称" prop="name">
              <el-input v-model="form.name" placeholder="请输入名称" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="参会时间" prop="time">
              <el-date-picker v-model="form.time" type="datetime" placeholder="请选择参会时间" valueFormat="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="地    点" prop="address">
              <el-input v-model="form.address" placeholder="请输入地点" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="内    容" prop="content">
              <el-input v-model="form.content" placeholder="请输入内容" type="textarea" rows="4" />
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="发送时间一" prop="reservationTime1">
              <el-date-picker v-model="form.reservationTime1" type="datetime" placeholder="请选择预约短信发送时间一" valueFormat="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row :gutter="15">
          <el-col>
            <el-form-item label="发送时间二" prop="reservationTime2">
              <el-date-picker v-model="form.reservationTime2" type="datetime" placeholder="请选择预约短信发送时间二" valueFormat="yyyy-MM-dd HH:mm:ss" style="width: 100%;">
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 单位详情 -->
    <DetailDialog :visible.sync="unitopen" :formUnit="formUnit" />

    <Dialog :form="form" :items="items" :resultOpen.sync="resultOpen" :rowspanList="rowspanList" />
    <MultiSet :visible.sync="multiSet" :setMulti="setMulti" />
  </div>
</template>

<script>
import {
  getUnit,
  delUnit,
  exportUnit,
  modifyDisable,
  forbiddenList,
  getGoingUnit,
  multiSet,
  sendSmg
} from "@/api/unit/unit";
import { getExtract } from "@/api/unit/extract";
import { listUnittype } from "@/api/unit/unittype";
import { getAgentList,getRandomresult } from "@/api/unit/random";
import unitDetail from "@/common/unitDetail/unitDetail";
import Dialog from "./components/Dialog";
import DetailDialog from "@/common/detailDialog";
import MultiSet from "./components/MultiSet";

export default {
  name: "sendsmg",
  components: { unitDetail, Dialog, DetailDialog, MultiSet },
  data() {
    const validateUnitNum = (rule, value, callback) => {
      if (value < 1) this.form.unitNum = 1;
      callback();
    }
    const validatemultipleNum = (rule, value, callback) => {
      if (value < 1) this.form.multipleNum = 1;
      callback();
    }
    return {
      // 遮罩层
      loading: true,
      //默认选中
      label: 0,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 单位信息表格数据
      unitList: [],
      // 单位信息表格数据
      agentList: [],
      // 弹出层标题
      title: "",
      valueID: "",//抽取库id
      // 是否显示弹出层
      open: false,
      // 单位类型字典
      unitTypeOptions: [],
      searchDoingStatus: [
        {
          label: "全部",
          value: 0,
        },
        {
          label: "有进行中的项目",
          value: 1,
        },
      ],
      // 查询参数
      queryParams: {
        forbidden: null,
        pageNum: 1,
        pageSize: 10,
        unitName: null,
        unitRepresentative: null,
        unitRepresentativePhone: null,
        unitInstitutionId: null,
        unitLinkman: null,
        unitPhone: null,
        unitType: null,
        unitEmail: null,
        unitBank: null,
        unitSort: null,
        unitNaturalGrade: null,
        unitNaturalScope: null,
        unitAddress: null,
        unitTypes: null,
        unitRemarks: null,
        unitStatues: null,
        unitNum: null,
        searchDoingStatus: 0,
      },
      unitTypeParams: {
        pageNum: 1,
        pageSize: 10,
        unittypeName: null,
      },
      modifyqueryParams: {
        forbidden: null,
        unitId: null,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "单位名称不能为空", trigger: "blur" },
        ],
        content: [
          { required: true, message: "会议内容不能为空", trigger: "change" },
        ],
        time: [
          { required: true, message: "时间不能为空", trigger: "blur" },
        ],
        address: [
          {
            required: true,
            message: "时间不能为空",
            trigger: "blur",
          },
        ]
      },
      unitopen: false,
      formUnit: {},
      unitDetailRow: {},
      onGoingProject: [],
      items: [],
      resultOpen: false,
      rowspanList: 5,
      multiSet: false,
      phoneNos: []
    };
  },
  created() {
    this.getList();
    listUnittype().then((response) => {
      this.unitTypeOptions = response.rows;
    });
  },
  methods: {
    /** 查询单位信息列表 */
    getList() {
      this.loading = true;
      //获取到选择的单位库
      this.valueID = this.queryParams.unitType;
      if(this.valueID != 15){
        forbiddenList(this.queryParams)
        .then((response) => {
          this.unitList = response.rows;
          this.total = response.total;
        })
        .finally(() => (this.loading = false));
      }else{
        getAgentList(this.queryParams).then(res => {
              this.agentList = res.rows;
              this.total = res.total;
          }).finally(() => this.loading = false);
      }
      
    },
    // 单位库类型翻译
    unitTypeFormat(row, column) {
      return this.selecttypeLabel(this.unitTypeOptions, row.unitType);
    },
    approveStatusFormat(row, column) {
      if (row.unitType == 1) {
        return "招标代理";
      } else if (row.unitType == 2) {
        return "施工图审查（含勘察报告审查）";
      } else if (row.unitType == 3) {
        return "预结算（含施工图预算清单编制、工程变更审核、结算内部）";
      } else if (row.unitType == 4) {
        return "工程财务决算";
      } else if (row.unitType == 5) {
        return "工程设计";
      } else if (row.unitType == 6) {
        return "工程勘察（含各阶段勘察工作、勘察外业见证）";
      } else if (row.unitType == 7) {
        return "工程监理";
      } else if (row.unitType == 8) {
        return "工程检测单位";
      } else if (row.unitType == 9) {
        return "预结算（跟踪审计）";
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      
    },
    //转换单位库类型
    selecttypeLabel(datas, value) {
      var actions = [];
      Object.keys(datas).some((key) => {
        if (datas[key].unittypeId == "" + value) {
          actions.push(datas[key].unittypeName);
          return true;
        }
      });
      return actions.join("");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      if(this.valueID != 15){
        this.phoneNos = selection.map((item) => item.unitRepresentativePhone);
      }else{
        this.phoneNos = selection.map((item) => item.telphone);
      }
      
      this.ids = selection.map((item) => item.unitId);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    handleSend() {
      if(this.phoneNos.length < 1) {
        this.$message.warning("请选择至少一个单位");
        return;
      }
      this.open = true;
      this.title = "发送短信";
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          console.log(this.form);
          sendSmg({...this.form, phoneNos: this.phoneNos}).then(res => {
            this.msgSuccess("发送成功");
            this.open = false;
            this.refs.form.resetFields();
          });
        }
      });
    },
    // 单位状态修改
    handleStatusChange(row) {
      let text = row.forbidden === "0" ? "启用" : "禁用";
      this.modifyqueryParams.forbidden = row.forbidden;
      this.modifyqueryParams.unitId = row.unitId;
      this.$confirm("确认要" + text + "该单位吗?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          modifyDisable(this.modifyqueryParams);
          this.msgSuccess(text + "成功");
        })
        .catch(function () {
          row.forbidden = row.forbidden === "0" ? "1" : "0";
        });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const unitIds = row.unitId || this.ids;
      this.$confirm(
        '是否确认删除单位信息编号为"' + unitIds + '"的数据项?',
        "警告",
        {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning",
        }
      )
        .then(function () {
          return delUnit(unitIds);
        })
        .then(() => {
          this.getList();
          this.msgSuccess("删除成功");
        });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有单位信息数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(function () {
          return exportUnit(queryParams);
        })
        .then((response) => {
          this.download(response.msg);
        });
    },
    handleStatus() {
      this.getList();
    },
    handleDetail(row) {
      this.unitDetailRow = row;
      getUnit(row.unitId).then((res) => {
        this.formUnit = res.data;
        this.unitopen = true;
      });
      getGoingUnit({ unitId: row.unitId }).then((res) => {
        this.onGoingProject = res.rows;
        this.onGoingProject.forEach((item, index) => {
          item.index = index + 1;
        });
      });
    },
    setMulti(multipleNum) {
      multiSet({ multipleNum }).then(res => {
        if (res.code == 200) {
          this.getList();
          this.multiSet = false;
        }
      })
    }
  },
};
</script>
<style lang="scss" scoped>
::v-deep .el-table .cell {
  overflow: hidden;
  white-space: nowrap;
  text-overflow: ellipsis;
}

::v-deep .el-table .cell:hover {
  white-space: normal;
}

.on-going-project {
  font-size: 18px;
  color: #303133;
  padding-left: 10px;
}

.going-project-table {
  padding: 20px 30px;
}

.clickable {
  cursor: pointer;
}
</style>
